const express = require('express');
const https = require('https');
const fs = require('fs');
const path = require('path');
const apiRouter = require('./routes/api');
const setupWebSocket = require('./websocket/websocket');
const certsDir = path.join(__dirname, '../../certs');
const options = {
  key: fs.readFileSync(path.join(certsDir, 'key.pem')),
  cert: fs.readFileSync(path.join(certsDir, 'cert.pem'))
}
const app = express();
const server = https.createServer(options, app);
app.use((req, res, next) => {
  res.header('Access-Control-Allow-Origin', '*'); // 允许任何域
  res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE'); // 允许的 HTTP 方法
  res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization'); // 允许的请求头
  next();
});
// 中间件
// app.use(express.json());
// app.use(express.urlencoded({ extended: true }));

// 对于 JSON 请求体
app.use(express.json({ limit: '5000mb' })); // 增加到50MB
// 对于 URL-encoded 请求体
app.use(express.urlencoded({ limit: '5000mb', extended: true }));

// API路由
app.use('/api', apiRouter);

// 设置WebSocket
setupWebSocket(server);

// 首页路由
app.get('/', (req, res) => {
  res.send('Express + WebSocket 服务已启动');
});

// 错误处理
app.use((err, req, res, next) => {
  console.error(err.stack);
  res.status(500).send('服务器错误!');
});

const PORT = process.env.PORT || 3000;
server.listen(PORT, () => {
  console.log(`服务器运行在 https://localhost:${PORT}`);
});